/*
 * @Author: Sean
 * @Date:   2019-09-09 01:25:22
 * @Last Modified by:   Sean
 * @Last Modified time: 2019-09-17 02:46:11
 */
import api from '@/api'


const state = () => ({
  //获取数据URL
  url: {
    "total": "",
    "get": "",
    "edit": ""
  },
  fields: [],
  //筛选条件
  where: {},
  //数据存储
  tableData: [],
  //页数信息
  page: [1, 5],
  //总页数
  total: 30,
  //页面大小
  size: 5,
  //当前页面
  current: 1,
  //当前密钥
  mak: "this7"
})


const mutations = {
  //设置当前密钥
  setMak: (state, value) => {
    state.mak = value;
  },
  //设置当前密钥
  setURL: (state, value) => {
    state.url = value
  },
  //设置当前筛选条件
  setWhere: (state, value) => {
    state.where = value
  },
  //设置当前筛选条件
  setTotal: (state, value) => {
    state.total = value
  },
  //设置当前筛选条件
  setSize: (state, value) => {
    state.size = value
  },
  //修改当前页面
  setCurrent: (state, value) => {
    state.current = value
  },
  setPage: (state, value) => {
    state.page = [state.current, state.size]
  },
  //设置当前筛选条件
  setTableData: (state, value) => {
    state.tableData = value
  },
  //清空数据
  clearState(state) {
    state.getDataUrl = "";
    state.where = {};
    state.tableData = [];
  }
}

const actions = {
  //获取表格数据
  getTableData({ dispatch, commit, state }) {
    let model = state.url.get.model;
    let action = state.url.get.action;
    console.log("筛选条件", [state.where, state.page]);
    api[model][action]({
      where: state.where,
      page: state.page
    }).then(response => {
      console.log("返回数据", response);
      commit('setTableData', response)
    });
  },
  //修改表格数据
  editTableData({ dispatch, commit, state }, data) {
    let model = state.url.edit.model;
    let action = state.url.edit.action;
    api[model][action](data).then(response => {
      console.log("返回数据", response);
      dispatch("getTableData");
    });
  },
  //异步操作
  onAsynchronous({
    dispatch,
    commit,
    state
  }, { model, action, data, callback }) {
    console.log("异步操作", [model, action, data, callback]);
    //commit('CHANGE_SETTING', data)
    api[model][action](data).then(response => {
      console.log("返回数据", response);
      if (typeof func == 'function') {
        console.log("为函数", callback);
        callback();
      }
      //重新获取数据
      dispatch("getTableData");
      //重新计算数据
      dispatch("getPageTotal");
    });
  },
  //页面跳转
  onCurrentChange({ dispatch, commit, state }, data) {
    //设置当前页
    commit('setCurrent', data);
    //设置分页条件
    commit('setPage');
    //执行数据获取
    dispatch('getTableData');
  },
  //获取页面总条数
  getPageTotal({ commit, state }, data) {
    let model = state.url.total.model;
    let action = state.url.total.action;
    api[model][action]({ where: state.where }).then(response => {
      console.log("返回总条数", response);
      commit('setTotal', response)
    });
  }
}

export default {
  state,
  mutations,
  actions
}
